package com.son.hotel.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.son.hotel.common.ErrorCode;
import com.son.hotel.common.Result;
import com.son.hotel.domain.Dishes;
import com.son.hotel.domain.RoomType;
import com.son.hotel.domain.Rooms;
import com.son.hotel.execption.BusinessException;
import com.son.hotel.response.RoomDetailInfoResp;
import com.son.hotel.service.DishesService;
import com.son.hotel.vo.SearchInfo;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/menu")
public class DishesController {

    @Autowired
    private DishesService dishesService;

    /**
     * 查询所有菜品
     * @return
     */
    @Operation(summary = "预定餐饮-查询")
    @GetMapping("/list/dishes")
    public Result<List<Dishes>> listDishes(){
        List<Dishes> list = dishesService.list();
        if (CollectionUtil.isEmpty(list)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"查询失败");
        }
        log.info("dishList:{}",list);
        return Result.success("200",list);
    }

    /**
     * 修改菜品(admin)
     * @param dishes
     * @return
     */
    @Operation(summary = "菜品管理-修改-admin")
    @PostMapping("/dishes/update")
    public Result<ErrorCode> updateDishes(@RequestBody Dishes dishes){
        if (BeanUtil.isEmpty(dishes)){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        log.info("dishes:{}",dishes);
        boolean result = dishesService.updateById(dishes);
        if (!result){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"更新失败");
        }
        return Result.success("200",ErrorCode.SUCCESS);
    }


    /**
     * 添加菜品
     * @param dishes
     * @return
     */
    @Operation(summary = "菜品管理-增加-admin")
    @PostMapping("/dishes/add")
    public Result<ErrorCode> addDishes(@RequestBody Dishes dishes){
        if (BeanUtil.isEmpty(dishes)){
            throw new BusinessException(ErrorCode.NULL_ERROR,"参数为空");
        }
        boolean save = dishesService.save(dishes);
        if (!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"插入失败");
        }
        return Result.success("200",ErrorCode.SUCCESS);
    }

    /**
     * 删除菜品
     * @param id
     * @return
     */
    @Operation(summary = "菜品管理-删除-admin")
    @DeleteMapping("/dishes/delete/{id}")
    public Result<ErrorCode> deleteDishes(@PathVariable int id){
        if (id<=0){
            throw new BusinessException(ErrorCode.PARAMETER_ERROR,"参数错误");
        }
        boolean result = dishesService.removeById(id);
        if (!result){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"删除失败");
        }
        return Result.success("200",ErrorCode.SUCCESS);
    }

    /**
     * 搜索菜品
     * @return
     */
    @Operation(summary = "菜品管理-搜索-admin")
    @PostMapping("/dishes/search")
    public Result<List<Dishes>> searchDishes(@RequestBody SearchInfo searchInfo){
        log.info("searchInfo:{}",searchInfo);
        String value = searchInfo.getValue();

        QueryWrapper<Dishes> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name",value);
        List<Dishes> list = dishesService.list(queryWrapper);
        if (CollectionUtil.isEmpty(list)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"查询失败");
        }
        return Result.success("200",list);
    }

    /**
     * 批量导出
     * @param name
     */
    @Operation(summary = "菜品管理-导出-admin")
    @GetMapping("/dishInfo/export")
    public void exportData(@RequestParam(required = false) String name, HttpServletResponse response) throws IOException, IOException {
        ExcelWriter writer = ExcelUtil.getWriter(true);
        List<Dishes> dishList = new ArrayList<>();
        //全部导出
        if(StringUtils.isBlank(name)){
            dishList = dishesService.list();
        }
        writer.write(dishList,true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode("菜品信息表","UTF-8")+".xlsx");
        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //将excel写入到输出流里，并设置用完流之后就关闭
        writer.flush(outputStream,true);
    }


    /**
     * 批量导入
     * @param file
     * @return
     * @throws IOException
     */
    @Operation(summary = "菜品管理-导入-admin")
    @PostMapping("/dishInfo/import")
    public Result<ErrorCode> importData(MultipartFile file) throws IOException {
        try {
            //获取inputStream流
            InputStream inputStream  = file.getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream);
            List<Dishes> dishList = reader.readAll(Dishes.class);
            log.info("list:{}",dishList);
            //插入菜品信息
            dishesService.saveBatch(dishList);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"文件上传失败");
        }
        return Result.success("200",ErrorCode.SUCCESS);
    }

}
